package com.simplehire.service;

import com.simplehire.entity.JobDescription;
import com.simplehire.entity.ResumeMatchResult;
import com.simplehire.model.User;
import com.simplehire.repository.JobDescriptionRepository;
import com.simplehire.repository.ResumeMatchResultRepository;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 岗位匹配服务类 - MVP V3核心功能
 */
@Service
@Transactional
public class JobMatchingService {
    
    private static final Logger logger = LoggerFactory.getLogger(JobMatchingService.class);
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Autowired
    private JobDescriptionRepository jobDescriptionRepository;
    
    @Autowired
    private ResumeMatchResultRepository matchResultRepository;
    
    @Autowired
    private DeepSeekService deepSeekService;
    
    @Autowired(required = false)
    private MockDeepSeekService mockDeepSeekService;
    
    /**
     * 创建岗位描述
     */
    public JobDescription createJobDescription(JobDescription jobDescription, User createdBy) {
        jobDescription.setCreatedBy(createdBy);
        jobDescription.setIsActive(true);
        return jobDescriptionRepository.save(jobDescription);
    }
    
    /**
     * 更新岗位描述
     */
    public JobDescription updateJobDescription(Long jobId, JobDescription updatedJob, User user) {
        JobDescription existingJob = jobDescriptionRepository.findByIdAndIsActiveTrue(jobId)
            .orElseThrow(() -> new IllegalArgumentException("岗位不存在或已被删除"));
        
        // 检查权限（只有创建者可以修改）
        if (!existingJob.getCreatedBy().getId().equals(user.getId())) {
            throw new IllegalArgumentException("您没有权限修改此岗位");
        }
        
        // 更新字段
        existingJob.setTitle(updatedJob.getTitle());
        existingJob.setDescription(updatedJob.getDescription());
        existingJob.setRequirements(updatedJob.getRequirements());
        existingJob.setSalaryRange(updatedJob.getSalaryRange());
        existingJob.setWorkLocation(updatedJob.getWorkLocation());
        existingJob.setExperienceLevel(updatedJob.getExperienceLevel());
        existingJob.setEducationLevel(updatedJob.getEducationLevel());
        existingJob.setRequiredSkills(updatedJob.getRequiredSkills());
        existingJob.setCompanyName(updatedJob.getCompanyName());
        existingJob.setCompanySize(updatedJob.getCompanySize());
        existingJob.setIndustry(updatedJob.getIndustry());
        existingJob.setJobType(updatedJob.getJobType());
        
        return jobDescriptionRepository.save(existingJob);
    }
    
    /**
     * 删除岗位描述（软删除）
     */
    public void deleteJobDescription(Long jobId, User user) {
        JobDescription job = jobDescriptionRepository.findByIdAndIsActiveTrue(jobId)
            .orElseThrow(() -> new IllegalArgumentException("岗位不存在或已被删除"));
        
        // 检查权限
        if (!job.getCreatedBy().getId().equals(user.getId())) {
            throw new IllegalArgumentException("您没有权限删除此岗位");
        }
        
        job.setIsActive(false);
        jobDescriptionRepository.save(job);
    }
    
    /**
     * 获取所有激活的岗位
     */
    public List<JobDescription> getAllActiveJobs() {
        return jobDescriptionRepository.findByIsActiveTrue();
    }
    
    /**
     * 根据ID获取岗位
     */
    public JobDescription getJobById(Long jobId) {
        return jobDescriptionRepository.findByIdAndIsActiveTrue(jobId)
            .orElseThrow(() -> new IllegalArgumentException("岗位不存在或已被删除"));
    }
    
    /**
     * 搜索岗位
     */
    public List<JobDescription> searchJobs(String title, String company, String location, 
                                          String industry, String experienceLevel, 
                                          String educationLevel, String jobType) {
        return jobDescriptionRepository.searchJobs(title, company, location, industry, 
                                                  experienceLevel, educationLevel, jobType);
    }
    
    /**
     * 核心功能：简历与岗位匹配分析
     */
    public ResumeMatchResult matchResumeWithJob(User user, Long jobId, String resumeText) {
        JobDescription job = getJobById(jobId);
        
        // 检查是否已经存在匹配结果
        Optional<ResumeMatchResult> existingResult = matchResultRepository.findByUserAndJobDescription(user, job);
        
        try {
            // 调用AI服务进行匹配分析
            String analysisResult = analyzeResumeJobMatch(resumeText, job);
            
            // 解析AI分析结果
            ResumeMatchResult matchResult = parseMatchAnalysis(analysisResult, user, job, resumeText);
            
            // 如果存在旧结果，更新；否则创建新的
            if (existingResult.isPresent()) {
                ResumeMatchResult existing = existingResult.get();
                updateMatchResult(existing, matchResult);
                return matchResultRepository.save(existing);
            } else {
                return matchResultRepository.save(matchResult);
            }
            
        } catch (Exception e) {
            logger.error("AI匹配分析失败，使用默认分析: {}", e.getMessage());
            // 使用默认分析方法
            ResumeMatchResult defaultResult = performDefaultMatching(user, job, resumeText);
            
            if (existingResult.isPresent()) {
                ResumeMatchResult existing = existingResult.get();
                updateMatchResult(existing, defaultResult);
                return matchResultRepository.save(existing);
            } else {
                return matchResultRepository.save(defaultResult);
            }
        }
    }
    
    /**
     * 调用AI服务进行简历岗位匹配分析
     */
    private String analyzeResumeJobMatch(String resumeText, JobDescription job) {
        String prompt = String.format("""
            请分析以下简历与岗位的匹配度，并以JSON格式返回详细的分析结果：
            
            【岗位信息】：
            岗位标题：%s
            岗位描述：%s
            岗位要求：%s
            必需技能：%s
            经验要求：%s
            学历要求：%s
            工作地点：%s
            
            【简历内容】：
            %s
            
            请严格按照以下JSON格式返回分析结果，不要添加任何其他文字：
            {
              "overallScore": 85.5,
              "skillsScore": 90.0,
              "experienceScore": 80.0,
              "educationScore": 85.0,
              "locationScore": 95.0,
              "matchedSkills": {
                "Java": "精通",
                "Spring Boot": "熟练",
                "MySQL": "了解"
              },
              "missingSkills": ["Docker", "Kubernetes"],
              "strengths": "技术栈匹配度高，项目经验丰富",
              "weaknesses": "缺乏容器化技术经验",
              "recommendations": "建议学习Docker和Kubernetes技术",
              "detailedAnalysis": "详细的匹配分析报告..."
            }
            
            评分标准：
            - 总分0-100分
            - 技能匹配度：根据简历技能与岗位要求的匹配程度
            - 经验匹配度：根据工作经验与岗位要求的匹配程度
            - 学历匹配度：根据教育背景与岗位要求的匹配程度
            - 地理位置匹配度：根据工作地点的匹配程度
            """, 
            job.getTitle(),
            job.getDescription(),
            job.getRequirements(),
            job.getRequiredSkills() != null ? String.join(", ", job.getRequiredSkills()) : "无特殊要求",
            job.getExperienceLevel() != null ? job.getExperienceLevel() : "无特殊要求",
            job.getEducationLevel() != null ? job.getEducationLevel() : "无特殊要求",
            job.getWorkLocation() != null ? job.getWorkLocation() : "不限",
            resumeText);
        
        try {
            return deepSeekService.sendPrompt(prompt);
        } catch (Exception e) {
            // 如果DeepSeek服务失败，尝试使用模拟服务
            if (mockDeepSeekService != null) {
                return generateMockMatchAnalysis(job, resumeText);
            }
            throw e;
        }
    }
    
    /**
     * 解析AI分析结果
     */
    private ResumeMatchResult parseMatchAnalysis(String analysisResult, User user, 
                                               JobDescription job, String resumeText) {
        try {
            // 尝试解析JSON格式的结果
            JsonNode jsonNode = objectMapper.readTree(analysisResult);
            
            ResumeMatchResult result = new ResumeMatchResult(user, job, resumeText);
            
            // 设置分数
            result.setOverallScore(jsonNode.path("overallScore").asDouble());
            result.setSkillsScore(jsonNode.path("skillsScore").asDouble());
            result.setExperienceScore(jsonNode.path("experienceScore").asDouble());
            result.setEducationScore(jsonNode.path("educationScore").asDouble());
            result.setLocationScore(jsonNode.path("locationScore").asDouble());
            
            // 设置匹配技能
            JsonNode matchedSkillsNode = jsonNode.path("matchedSkills");
            if (matchedSkillsNode.isObject()) {
                Map<String, String> matchedSkills = new HashMap<>();
                matchedSkillsNode.fields().forEachRemaining(entry -> 
                    matchedSkills.put(entry.getKey(), entry.getValue().asText()));
                result.setMatchedSkills(matchedSkills);
            }
            
            // 设置缺失技能
            JsonNode missingSkillsNode = jsonNode.path("missingSkills");
            if (missingSkillsNode.isArray()) {
                List<String> missingSkills = new ArrayList<>();
                missingSkillsNode.forEach(node -> missingSkills.add(node.asText()));
                result.setMissingSkills(missingSkills);
            }
            
            // 设置分析内容
            result.setStrengths(jsonNode.path("strengths").asText());
            result.setWeaknesses(jsonNode.path("weaknesses").asText());
            result.setRecommendations(jsonNode.path("recommendations").asText());
            result.setDetailedAnalysis(jsonNode.path("detailedAnalysis").asText());
            
            return result;
            
        } catch (Exception e) {
            logger.warn("解析AI分析结果失败，使用文本解析: {}", e.getMessage());
            // 如果JSON解析失败，尝试文本解析
            return parseTextMatchAnalysis(analysisResult, user, job, resumeText);
        }
    }
    
    /**
     * 解析文本格式的分析结果
     */
    private ResumeMatchResult parseTextMatchAnalysis(String analysisResult, User user, 
                                                   JobDescription job, String resumeText) {
        ResumeMatchResult result = new ResumeMatchResult(user, job, resumeText);
        
        // 简单的文本解析逻辑
        result.setOverallScore(75.0); // 默认分数
        result.setSkillsScore(70.0);
        result.setExperienceScore(75.0);
        result.setEducationScore(80.0);
        result.setLocationScore(85.0);
        
        result.setDetailedAnalysis(analysisResult);
        result.setStrengths("基于文本分析的优势评估");
        result.setWeaknesses("基于文本分析的劣势评估");
        result.setRecommendations("基于文本分析的改进建议");
        
        return result;
    }
    
    /**
     * 默认匹配分析（当AI服务不可用时）
     */
    private ResumeMatchResult performDefaultMatching(User user, JobDescription job, String resumeText) {
        ResumeMatchResult result = new ResumeMatchResult(user, job, resumeText);
        
        // 基础的关键词匹配分析
        double skillsScore = calculateSkillsMatch(resumeText, job.getRequiredSkills());
        double experienceScore = calculateExperienceMatch(resumeText, job.getExperienceLevel());
        double educationScore = calculateEducationMatch(resumeText, job.getEducationLevel());
        double locationScore = calculateLocationMatch(resumeText, job.getWorkLocation());
        
        // 计算总分（加权平均）
        double overallScore = (skillsScore * 0.4 + experienceScore * 0.3 + 
                              educationScore * 0.2 + locationScore * 0.1);
        
        result.setOverallScore(overallScore);
        result.setSkillsScore(skillsScore);
        result.setExperienceScore(experienceScore);
        result.setEducationScore(educationScore);
        result.setLocationScore(locationScore);
        
        result.setStrengths("基于关键词匹配的优势分析");
        result.setWeaknesses("基于关键词匹配的劣势分析");
        result.setRecommendations("建议完善简历内容，突出相关技能和经验");
        result.setDetailedAnalysis("这是基于关键词匹配的默认分析结果");
        
        return result;
    }
    
    /**
     * 计算技能匹配度
     */
    private double calculateSkillsMatch(String resumeText, List<String> requiredSkills) {
        if (requiredSkills == null || requiredSkills.isEmpty()) {
            return 80.0; // 如果没有特殊技能要求，给予默认分数
        }
        
        String resumeLower = resumeText.toLowerCase();
        int matchedCount = 0;
        
        for (String skill : requiredSkills) {
            if (resumeLower.contains(skill.toLowerCase())) {
                matchedCount++;
            }
        }
        
        return (double) matchedCount / requiredSkills.size() * 100;
    }
    
    /**
     * 计算经验匹配度
     */
    private double calculateExperienceMatch(String resumeText, String experienceLevel) {
        if (experienceLevel == null || experienceLevel.isEmpty()) {
            return 80.0;
        }
        
        // 简单的经验匹配逻辑
        String resumeLower = resumeText.toLowerCase();
        if (resumeLower.contains("年") || resumeLower.contains("经验")) {
            return 75.0;
        }
        return 60.0;
    }
    
    /**
     * 计算学历匹配度
     */
    private double calculateEducationMatch(String resumeText, String educationLevel) {
        if (educationLevel == null || educationLevel.isEmpty()) {
            return 80.0;
        }
        
        String resumeLower = resumeText.toLowerCase();
        if (resumeLower.contains("本科") || resumeLower.contains("学士") || 
            resumeLower.contains("硕士") || resumeLower.contains("博士")) {
            return 85.0;
        }
        return 70.0;
    }
    
    /**
     * 计算地理位置匹配度
     */
    private double calculateLocationMatch(String resumeText, String workLocation) {
        if (workLocation == null || workLocation.isEmpty()) {
            return 90.0;
        }
        
        String resumeLower = resumeText.toLowerCase();
        String locationLower = workLocation.toLowerCase();
        
        if (resumeLower.contains(locationLower)) {
            return 95.0;
        }
        return 70.0; // 默认可以接受异地工作
    }
    
    /**
     * 生成模拟匹配分析
     */
    private String generateMockMatchAnalysis(JobDescription job, String resumeText) {
        return String.format("""
            {
              "overallScore": 78.5,
              "skillsScore": 75.0,
              "experienceScore": 80.0,
              "educationScore": 85.0,
              "locationScore": 75.0,
              "matchedSkills": {
                "Java": "熟练",
                "Spring": "了解"
              },
              "missingSkills": ["Docker", "微服务"],
              "strengths": "技术基础扎实，学习能力强",
              "weaknesses": "缺乏部分新技术经验",
              "recommendations": "建议加强云原生技术学习",
              "detailedAnalysis": "候选人与岗位 '%s' 的匹配度为78.5分，整体表现良好。"
            }
            """, job.getTitle());
    }
    
    /**
     * 更新匹配结果
     */
    private void updateMatchResult(ResumeMatchResult existing, ResumeMatchResult newResult) {
        existing.setResumeText(newResult.getResumeText());
        existing.setOverallScore(newResult.getOverallScore());
        existing.setSkillsScore(newResult.getSkillsScore());
        existing.setExperienceScore(newResult.getExperienceScore());
        existing.setEducationScore(newResult.getEducationScore());
        existing.setLocationScore(newResult.getLocationScore());
        existing.setMatchedSkills(newResult.getMatchedSkills());
        existing.setMissingSkills(newResult.getMissingSkills());
        existing.setStrengths(newResult.getStrengths());
        existing.setWeaknesses(newResult.getWeaknesses());
        existing.setRecommendations(newResult.getRecommendations());
        existing.setDetailedAnalysis(newResult.getDetailedAnalysis());
    }
    
    /**
     * 获取用户的匹配历史
     */
    public List<ResumeMatchResult> getUserMatchHistory(User user) {
        return matchResultRepository.findByUserOrderByCreatedAtDesc(user);
    }
    
    /**
     * 获取岗位的匹配结果
     */
    public List<ResumeMatchResult> getJobMatchResults(Long jobId) {
        JobDescription job = getJobById(jobId);
        return matchResultRepository.findByJobDescriptionOrderByOverallScoreDesc(job);
    }
    
    /**
     * 获取用户统计信息
     */
    public UserMatchStats getUserStats(User user) {
        List<ResumeMatchResult> results = getUserMatchHistory(user);
        
        if (results.isEmpty()) {
            return new UserMatchStats(0, 0.0, 0.0, 0);
        }
        
        double avgScore = results.stream()
            .mapToDouble(ResumeMatchResult::getOverallScore)
            .average().orElse(0.0);
        
        double maxScore = results.stream()
            .mapToDouble(ResumeMatchResult::getOverallScore)
            .max().orElse(0.0);
        
        long highScoreCount = results.stream()
            .mapToDouble(ResumeMatchResult::getOverallScore)
            .filter(score -> score >= 80.0)
            .count();
        
        return new UserMatchStats(results.size(), avgScore, maxScore, (int) highScoreCount);
    }
    
    /**
     * 用户匹配统计信息
     */
    public static class UserMatchStats {
        private final int totalMatches;
        private final double averageScore;
        private final double bestScore;
        private final int highScoreMatches;
        
        public UserMatchStats(int totalMatches, double averageScore, double bestScore, int highScoreMatches) {
            this.totalMatches = totalMatches;
            this.averageScore = averageScore;
            this.bestScore = bestScore;
            this.highScoreMatches = highScoreMatches;
        }
        
        public int getTotalMatches() { return totalMatches; }
        public double getAverageScore() { return averageScore; }
        public double getBestScore() { return bestScore; }
        public int getHighScoreMatches() { return highScoreMatches; }
    }
}